<template>
  <div>
    <Card _Title="我的分销" :_Size="16"></Card>
    <!-- 分销申请 -->
    <div v-if="status === '0'">
      <a-alert type="warning" class="mt_20 mb_10">分销商申请</a-alert>
      <a-form ref="applyFormRef" :model="applyForm" size="large" layout="horizontal" auto-label-width class="mt_20" @submit-success="handleSubmitApply">
        <a-form-item field="name" label="姓名" :rules="[REQUIRED]">
          <a-input v-model="applyForm.name" allow-clear placeholder="请填写您的姓名"></a-input>
        </a-form-item>
        <a-form-item field="idNumber" label="身份证号" :rules="[REQUIRED, IDCARD]">
          <a-input v-model="applyForm.idNumber" allow-clear placeholder="请填写您的身份证号"></a-input>
        </a-form-item>
        <a-form-item style="color: #999999;" class="tip">
          <a-checkbox v-model="isReadAndAgree">已阅读并同意《<span class="hover-pointer global-color" @click.stop="goArticle('1751868518633123841')">lilishop分销推广协议</span>》</a-checkbox>
          <div class="mt_10 fontsize-13">您的申请信息将提交至平台审核，审核期间将会给您致电，请保持手机畅通。</div>
        </a-form-item>
        <a-form-item field="" label="">
          <a-button html-type="submit" size="small" status="danger" type="primary" :loading="applyLoading">提交申请</a-button>
        </a-form-item>
      </a-form>
    </div>
    <!-- 分销审核 -->
    <div v-if="status === '1'">
      <a-alert type="success"><template #title>您提交的信息正在审核</template>提交认证申请后，工作人员将在三个工作日进行核对完成审核</a-alert>
    </div>
    <!-- 分销提现、商品、订单 -->
    <div v-if="status === '2'">
      <div class="tips pt_10 pb_10 pl_20"><p>分销下线付款之后会生成分销订单。</p><p>交易完成后返佣可提现。</p></div>
      <div class="mt_10 mb_20 account-price">
        <span class="subTips">可提现金额(元)：</span>
        <span class="price-color mr_20" style="font-size: 42px;">{{ unitPrice(Number(disResult.canRebate)) }}</span>
        <span class="subTips">待结算：</span>
        <span class="price-color mr_10">{{ unitPrice(disResult.commissionFrozen) }}</span>
        <span class="subTips">总收益(元)：</span>
        <span class="price-color mr_10">{{ unitPrice(disResult.rebateTotal) }}</span>
        <a-button @click="withdrawApplyModal = true" size="small" status="danger" type="outline" class="ml_10">申请提现</a-button>
      </div>
      <a-tabs v-model:active-key="tabName" @change="tabsChange">
        <a-tab-pane key="order" title="推广订单">
          <a-table :columns="orderColumns" :data="orderData.records" :pagination="false">
            <template #rebate="{ record }"><span>{{unitPrice(record.rebate, '￥')}}</span></template>
            <template #distributionOrderStatus="{ record }">
              <span v-if="record.distributionOrderStatus === 'NO_COMPLETED'">未完成</span>
              <span v-else-if="record.distributionOrderStatus === 'COMPLETE'">订单完成</span>
              <span v-else-if="record.distributionOrderStatus === 'CANCEL'">订单取消</span>
              <span v-else-if="record.distributionOrderStatus === 'REFUND'">订单退款</span>
            </template>
          </a-table>
          <div class="paginationBox">
            <a-pagination :total="orderData.total" :page-size="orderParams.pageSize" :current="orderParams.pageNumber" show-jumper @change="changePage($event, 'order')"></a-pagination>
          </div>
        </a-tab-pane>
        <a-tab-pane key="goods" title="推广商品">
          <a-table :columns="goodsColumns" :data="goodsData.records" :pagination="false">
            <template #name="{ record }">
              <div class="goods-msg hover-color hover-pointer" @click="goGoodsDetail(record.skuId, record.goodsId)">
                <img :src="record.thumbnail" width="60" height="60" alt=""/>{{ record.goodsName }}
              </div>
            </template>
            <template #price="{ record }"><span>{{unitPrice(record.price, '￥')}}</span></template>
            <template #firstProportion="{ record }"><span>{{ record.firstProportion }}%</span></template>
            <template #commission="{ record }"><span>{{unitPrice(record.commission, '￥')}}</span></template>
            <template #action="{ record }">
              <a-button @click="fenxiao(record)" size="mini" status="success" type="outline">邀请好友</a-button>
            </template>
          </a-table>
          <div class="paginationBox">
            <a-pagination :total="goodsData.total" :page-size="goodsParams.pageSize" :current="goodsParams.pageNumber" show-jumper @change="changePage($event, 'goods')"></a-pagination>
          </div>
        </a-tab-pane>
        <a-tab-pane key="member" title="我的客户">
          <a-table :columns="memberColumns" :data="memberData.records" :pagination="false">
            <template #orderPrice="{ record }"><span>{{unitPrice(record.orderPrice, '￥')}}</span></template>
            <template #rebatePrice="{ record }"><span>{{unitPrice(record.rebatePrice, '￥')}}</span></template>
          </a-table>
          <div class="paginationBox">
            <a-pagination :total="memberData.total" :page-size="memberParams.pageSize" :current="memberParams.pageNumber" show-jumper @change="changePage($event, 'member')"></a-pagination>
          </div>
        </a-tab-pane>
        <a-tab-pane key="log" title="提现记录">
          <a-table :columns="logColumns" :data="logData.records" :pagination="false">
            <template #price="{ record }">
              <span v-if="record.distributionCashStatus === 'VIA_AUDITING'" style="color: #00B42A;">{{ unitPrice(record.price, '￥') }}</span>
              <span v-else style="color: #F31947;">{{ unitPrice(record.price, '￥') }}</span>
            </template>
            <template #status="{ record }">
              <span v-if="record.distributionCashStatus==='APPLY'">待处理</span>
              <span v-else-if="record.distributionCashStatus==='VIA_AUDITING'">通过</span>
              <span v-else>拒绝</span>
            </template>
          </a-table>
          <div class="paginationBox">
            <a-pagination :total="logData.total" :page-size="logParams.pageSize" :current="logParams.pageNumber" show-jumper @change="changePage($event, 'log')"></a-pagination>
          </div>
        </a-tab-pane>
        <a-tab-pane key="group" title="我的团队">
          <a-table :columns="groupColumns" :data="groupData.records" :pagination="false">
            <template #distributionOrderPrice="{ record }"><span>{{unitPrice(record.distributionOrderPrice, '￥')}}</span></template>
          </a-table>
          <div class="paginationBox">
            <a-pagination :total="groupData.total" :page-size="groupParams.pageSize" :current="groupParams.pageNumber" show-jumper @change="changePage($event, 'group')"></a-pagination>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>
    <!-- 未开放 -->
    <div v-if="status === '3'">
      <a-alert type="error"><template #title>分销功能暂未开启</template></a-alert>
    </div>
    <!-- 分销资格被清退 -->
    <div v-if="status === '4'">
      <a-alert type="error"><template #title>您的分销资格已被清退。</template>您的分销资格已被清退。请联系管理员或进行申诉</a-alert>
      <a-button size="small" status="warning" type="primary" class="mt_20" @click="repaying">申诉</a-button>
    </div>
    <!-- 分销申诉审核 -->
    <div v-if="status === '5'">
      <a-alert type="success"><template #title>您提交的申诉正在审核</template>提交认证申请后，工作人员将在三个工作日进行核对完成审核</a-alert>
    </div>
    <!--提现申请modal-->
    <a-modal v-model:visible="withdrawApplyModal">
      <template #title>提现申请</template>
      <div class="">
        <a-form ref="withdrawApplyFormRef" size="large" layout="horizontal" :style="{ width: '400px'}" auto-label-width :model="withdrawApplyForm">
          <a-form-item field="withdrawPrice" label="提现金额" :rules="[REQUIRED, SUM]">
            <a-input-number v-model="withdrawApplyForm.withdrawPrice" :min="0"><template #append>元</template></a-input-number>
          </a-form-item>
        </a-form>
      </div>
      <template #footer>
        <a-button @click="withdrawalSubmit" status="success" type="outline">提现</a-button>
      </template>
    </a-modal>
    <!-- 分销商品modal -->
    <a-modal v-model:visible="qrcodeModal" width="700px">
      <template #title>分销商品</template>
      <a-alert type="warning" class="mt_20 mb_10">下载二维码或者复制链接分享商品</a-alert>
      <div class="codeList flex">
        <div>
          <div style="width: 200px; height: 200px; border: 1px solid transparent;line-height: 200px;font-size: 26px;">PC端</div>
          <div class="platform mt_10 mb_10" style="height: 22px"></div>
          <a-button @click="copyUrlLink()" size="small" status="success" type="outline">复制链接</a-button>
        </div>
        <div>
          <div style="width: 200px; height: 200px; border: 1px solid #eee" id="qr-code-box">
            <vue-qrcode v-if="qrcodeH5" :value="qrcodeH5" :options="qrcodeOptions"></vue-qrcode>
          </div>
          <div class="platform mt_10 mb_10">移动应用端</div>
          <a-button @click="downloadQrcodeH5()" size="small" status="success" type="outline">下载二维码</a-button>
        </div>
      </div>
      <template #footer>
        <a-button @click="qrcodeModal = false" status="danger" type="primary">确定</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import { unitPrice } from '@/utils/filters';
  import { REQUIRED, SUM, IDCARD } from '@/utils/validator';
  import { Message } from '@arco-design/web-vue';
  import config from '@/config/index';
  import { distribution, applyDistribution, distCash, distCashHistory, getDistGoodsList, getDistOrderList, getDistMemberList, getDistGroupList } from "@/api/distribution";
  import VueQrcode from '@chenfengyuan/vue-qrcode';

  const router = useRouter();
  const status = ref('0'); // 申请状态，0为未申请 1 申请中 2 申请完成 3 功能暂未开启
  // 分销商申请表单
  const applyForm = ref({name: '', idNumber: ''});
  const applyFormRef = ref();
  const isReadAndAgree = ref(false);  // 是否阅读并同意
  const tabName = ref("order"); // 当前所在tab
  const disResult = ref<any>({}); // 审核结果
  const applyLoading = ref(false); // 申请加载状态
  const withdrawApplyModal = ref(false); // 提现表单modal
  // 提现金额表单
  const withdrawApplyFormRef = ref();
  const withdrawApplyForm = ref({ withdrawPrice: 0 });
  // 推广订单
  const orderParams = ref({pageNumber: 1, pageSize: 20, sort: "createTime", order: "desc"});
  const orderData = ref<any>({});
  const orderColumns: any = [
    {title: '下单时间', dataIndex: 'createTime', align: 'center' },
    {title: '商品名称', dataIndex: 'goodsName', slotName: '', align: 'center' },
    {title: '数量', dataIndex: 'num', slotName: '', align: 'center' },
    {title: '佣金金额', dataIndex: 'rebate', slotName: 'rebate', align: 'center' },
    {title: '状态', dataIndex: 'distributionOrderStatus', slotName: 'distributionOrderStatus', align: 'center' },
  ];
  // 推广商品
  const goodsParams = ref({pageNumber: 1, pageSize: 10, sort: "createTime", order: "desc"});
  const goodsData = ref<any>({});
  const goodsColumns: any = [
    {title: '商品名称', dataIndex: 'name', slotName: 'name', align: 'left', width: 450 },
    {title: '商品价格', dataIndex: 'price', slotName: 'price', align: 'center' },
    {title: '佣金比例', dataIndex: 'firstProportion', slotName: 'firstProportion', align: 'center' },
    {title: '预计赚', dataIndex: 'commission', slotName: 'commission', align: 'center' },
    {title: '操作', dataIndex: '', slotName: 'action', align: 'center' },
  ];
  // 我的客户
  const memberParams = ref({pageNumber: 1, pageSize: 20, sort: "createTime", order: "desc"});
  const memberData = ref<any>({});
  const memberColumns: any = [
    {title: '客户昵称', dataIndex: 'nickName', slotName: '', align: 'center' },
    {title: '成交额', dataIndex: 'orderPrice', slotName: 'orderPrice', align: 'center' },
    {title: '佣金总额', dataIndex: 'rebatePrice', slotName: 'rebatePrice', align: 'center' },
    {title: '订单数', dataIndex: 'orderNum', slotName: '', align: 'center' },
    {title: '最近下单时间', dataIndex: 'lastLoginDate', slotName: '', align: 'center' }
  ];
  // 提现记录
  const logParams = ref({pageNumber: 1, pageSize: 20, sort: "createTime", order: "desc"});
  const logData = ref<any>({});
  const logColumns: any = [
    {title: '编号', dataIndex: 'sn', slotName: '', align: 'center' },
    {title: '申请时间', dataIndex: 'createTime', slotName: '', align: 'center' },
    {title: '提现金额', dataIndex: 'price', slotName: 'price', align: 'center' },
    {title: '提现状态', dataIndex: 'status', slotName: 'status', align: 'center' }
  ];
  // 我的团队
  const groupParams = ref({pageNumber: 1, pageSize: 20, sort: "createTime", order: "desc"});
  const groupData = ref<any>({}); //团队数据
  const groupColumns: any = [
    {title: '昵称', dataIndex: 'memberName', slotName: '', align: 'center' },
    {title: '销售额', dataIndex: 'distributionOrderPrice', slotName: 'distributionOrderPrice', align: 'center' },
    {title: '订单量', dataIndex: 'distributionOrderCount', slotName: '', align: 'center' }
  ];
  // 二维码
  const qrcode = ref(""); // 二维码链接PC
  const qrcodeH5 = ref(""); // 二维码链接H5
  const qrcodeOptions = ref({ width: 200, height: 200 }); // 二维码参数
  const qrcodeModal = ref(false); // 显示二维码modal
  const goodsNameCurr = ref(""); // 当前分销商品名称

  // 申请成为分销商
  const handleSubmitApply =async  () => {
    const auth = await applyFormRef.value?.validate();
    if (!auth) {
      if (!isReadAndAgree.value) {
        Message.warning("请先阅读并同意lilishop分销推广协议");
      } else {
        applyLoading.value = true;
        applyDistribution(applyForm.value).then((res) => {
          applyLoading.value = false;
          if (res.data.success) {
            Message.success("申请已提交，请等待管理员审核");
            status.value = '1';
          }
        });
      }
    }
  };
  // 申诉
  const repaying = () => {
    applyDistribution().then((res) => {
      applyLoading.value = false;
      if (res.data.success) {
        Message.success("申诉已提交，请等待管理员审核");
      }
    });
  };

  // 获取分销商信息
  const getDistribution = () => {
    distribution().then((res) => {
      if (res.data.result) {
        disResult.value = res.data.result;
        let type = res.data.result.distributionStatus;
        // 0为未申请 1 申请中 2 申请完成 3 功能暂未开启
        if (type === "PASS") {
          status.value = '2';  // 申请完成
          getOrderData();
        } else if (type === "REFUSE") {
          status.value = '0';  // 未申请
        } else if (type === "RETREAT") {
          status.value = '4'; // 分销资格被清退
        } else if (type === "APPEAL") {
          status.value = '5'; // 申诉
        } else {
          status.value = '1';  // 申请中
        }
      } else if (res.data.success && res.data.code === 22000) {
        status.value = '3';  // 功能暂未开启
      } else {
        // 没有资格申请 先去实名认证
        status.value = '0';
      }
    });
  };
  // 跳转商品详情
  const goGoodsDetail = (skuId: any, goodsId: any) => {
    let routeUrl = router.resolve({path: "/goodsDetail", query: { skuId, goodsId },});
    window.open(routeUrl.href, "_blank");
  };
  // 分销商品--邀请好友
  const fenxiao = (row: any) => {
    qrcode.value = `${config.PC_DOMAIN}/goodsDetail?skuId=${row.skuId}&goodsId=${row.goodsId}&distributionId=${disResult.value.id}`;
    qrcodeH5.value = `${config.WAP_DOMAIN}/#/pages/goods/product/detail?skuId=${row.skuId}&goodsId=${row.goodsId}&distributionId=${disResult.value.id}`;
    goodsNameCurr.value = row.goodsName;
    qrcodeModal.value = true;
  };
  // 复制链接
  const copyUrlLink = () => {
    navigator.clipboard.writeText(qrcode.value).then(() => {
        Message.success("复制成功！");
      }).catch(err => {
        Message.error("复制失败！");
      });
  };
  // 下载H5二维码
  const downloadQrcodeH5 = () => {
    //获取canvas标签
    let canvas = document.getElementById('qr-code-box')!.getElementsByTagName('canvas');
    //创建a标签
    let a = document.createElement('a');
    //获取二维码的url并赋值为a.href
    a.href = canvas[0].toDataURL('img/png');
    //设置下载文件的名字
    a.download = goodsNameCurr.value;
    //点击事件，相当于下载
    a.click();
    //提示信息
    Message.warning('下载中，请稍后...');
  };
  // 申请提现
  const withdrawalSubmit = async () => {
    const auth = await withdrawApplyFormRef.value?.validate();
    if (!auth) {
      distCash({price: withdrawApplyForm.value.withdrawPrice}).then((res) => {
        withdrawApplyModal.value = false;
        if (res.data.success) {
          Message.success("申请已提交，请等待审核");
          getDistribution();
          getLogData();
        } else {
          Message.error(res.data.message);
        }
      });
    }
  };
  // 订单数据
  const getOrderData = () =>{
    getDistOrderList(orderParams.value).then((res) => {
      if (res.data.success) orderData.value = res.data.result;
    });
  };
  // 商品数据
  const getGoodsData = () => {
    getDistGoodsList(goodsParams.value).then((res) => {
      if (res.data.success) goodsData.value = res.data.result;
    });
  };
  // 客户数据
  const getMemberData = () =>{
    getDistMemberList(memberParams.value).then((res) => {
      if (res.data.success) memberData.value = res.data.result;
    });
  };
  // 提现记录
  const getLogData = () => {
    distCashHistory(logParams.value).then((res) => {
      if (res.data.success) logData.value = res.data.result;
    });
  };
  // 我的团队数据
  const getGroupData = () => {
    getDistGroupList(groupParams.value).then((res) => {
      if (res.data.success) groupData.value = res.data.result;
    });
  };
  // tab栏切换
  const tabsChange = (tab: any) => {
    if (tab === "order") {
      // orderParams.value.checked = false;
      orderParams.value.pageNumber = 1;
      getOrderData();
    }else if (tab === "goods") {
      // params.value.checked = false;
      goodsParams.value.pageNumber = 1;
      getGoodsData();
    }else if (tab === "member") {
      // memberParams.value.checked = false;
      memberParams.value.pageNumber = 1;
      getMemberData();
    } else if (tab === "log") {
      logParams.value.pageNumber = 1;
      getLogData();
    }else if (tab === "group") {
      groupParams.value.pageNumber = 1;
      getGroupData();
    }
  };
  // 分页页数改变时触发
  const changePage = (event: any, type: any) => {
    if (type === 'order') {
      orderParams.value.pageNumber = event;
      getOrderData();
    } else if (type === 'goods') {
      goodsParams.value.pageNumber = event;
      getGoodsData();
    } else if (type === 'member') {
      memberParams.value.pageNumber = event;
      getMemberData();
    } else if (type === "log") {
      logParams.value.pageNumber = event;
      getLogData();
    }else if (type === "group") {
      groupParams.value.pageNumber = event;
      getGroupData();
    }
  };
  // 跳转文章详情（分销推广协议）
  const goArticle = (id: any) => {
    let routeUrl = router.resolve({path: '/article', query: { id }});
    window.open(routeUrl.href, '_blank');
  };
  onMounted(() => {
    getDistribution();
  })
</script>

<style scoped lang="less">
  .tips {
    background: @light_background_color;
    border-radius: 4px;
    > p {
      margin: 6px 0;
    }
  }
  .account-price {
    font-weight: bold;
  }
  .goods-msg {
    display: flex;
    align-items: center;
    padding: 3px;
    img {
       flex-shrink: 0;
      vertical-align: top;
      margin-right: 20px;
    }
  }

  .codeList {
    justify-content: center;
    text-align: center;
    > div {
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    > div:nth-of-type(1) {
      margin-right: 50px;
    }
  }
  .tip {
    :deep(.arco-form-item-content) {
      display: block;
    }
  }
</style>
